package com.qdsg.ysg.doctor.ui.activity.prescription;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.eventbus.PrescriptionAchieveEvent;
import com.qdsg.ysg.doctor.ui.MouldActivity;
import com.qdsg.ysg.doctor.ui.activity.mine.SignatureActivity;
import com.qdsg.ysg.doctor.ui.adapter.AddMedicineListAdapter;
import com.qdsg.ysg.doctor.ui.adapter.SecondListAdapter;
import com.qdsg.ysg.doctor.ui.dialog.Finish3Dialog;
import com.qdsg.ysg.doctor.ui.dialog.Item2Dialog;
import com.qdsg.ysg.doctor.ui.dialog.ItemDialog;
import com.qdsg.ysg.doctor.ui.dialog.MedicineListDialog;
import com.qdsg.ysg.doctor.ui.dialog.SaveDialog;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.exception.BusinessException;
import com.rest.response.AuthOauthVo;
import com.rest.response.BaseStringResponse;
import com.rest.response.MouldListResponse;
import com.rest.response.MouldResponse;
import com.rest.response.OauthStatusResponse;
import com.rest.response.PrescriptionListResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.UtilList;

import static com.qdsg.ysg.doctor.base.BaseApplication.prescriptionHashMap;

/**
 * 主诊断与次诊断通过病历带入，不能修改   开处方
 * Created by lbj on 2021/8/23 15:49
 * @author DELL
 */
public class AddPrescriptionActivity extends BaseActivity {
    @BindView(R.id.edt_advice)
    EditText edt_advice;
    @BindView(R.id.edt_notice)
    EditText edt_notice;
    @BindView(R.id.pre)
    TextView pre;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.second_recyclerView)
    RecyclerView second_recyclerView;
    @BindView(R.id.tv_is_child)
    CheckBox tv_is_child;
    @BindView(R.id.btn_yuannei)
    RadioButton btn_yuannei;
    @BindView(R.id.btn_guoyao)
    RadioButton btn_guoyao;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.tv_mould_name)
    TextView tvMouldName;
    @BindView(R.id.second_add)
    ImageView secondAdd;
    @BindView(R.id.second_diagnose)
    LinearLayout secondDiagnose;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.btn_add)
    ImageView btnAdd;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    @BindView(R.id.sv_all)
    ScrollView svAll;

    AddMedicineListAdapter adapter;
    SecondListAdapter secondAdapter;

    List<PrescriptionListResponse.Prescription> list = new ArrayList<>();
    List<PrescriptionListResponse.Second> list2 = new ArrayList<>();
    List<PrescriptionListResponse.pInfo> pInfoList = new ArrayList<>();

    String diagnoseId, preAppendId, icdId, tailAppendId, preAppend, diagnoseResult, icd;
    MouldResponse.Mould mould;
    Finish3Dialog mFinish3Dialog;
    @BindView(R.id.tv_mould_tip)
    TextView tvMouldTip;
    int type;
    private boolean isClearMould = false, isChooseMould = false, isGuoYao = false;
    private PrescriptionListResponse.pInfo pInfo;
    private String prescriptionId = "";

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_add_prescription;
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void initViews() {
        EventBus.getDefault().register(this);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new AddMedicineListAdapter(this, list);
        recyclerView.setAdapter(adapter);
        LinearLayoutManager manager2 = new LinearLayoutManager(this);
        manager2.setOrientation(LinearLayoutManager.VERTICAL);
        second_recyclerView.setLayoutManager(manager2);
        secondAdapter = new SecondListAdapter(this, list2, isGuoYao);
        second_recyclerView.setAdapter(secondAdapter);
        if (UtilString.isEmpty(icd)) {//主诊断为空
            secondAdapter.notifyDataSetChanged();
        }

        tv_is_child.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                tv_is_child.setText("是");
            } else {
                tv_is_child.setText("否");
            }
        });
    }


    @SuppressLint("SetTextI18n")
    @Override
    protected void initData() {
        diagnoseId = getIntent().getStringExtra("diagnoseId");
        LogUtil.e("prescriptionHashMap-----", prescriptionHashMap.size() + "" + "----" + icd);
        queryPrescriptionList();
        pInfo = new PrescriptionListResponse().new pInfo();

        if (UtilString.isEmpty(icd)) {
            secondDiagnose.setVisibility(View.VISIBLE);
        } else {//主诊断不为空
            edt_advice.setFocusable(false);
            edt_advice.setFocusableInTouchMode(false);
        }
        if (prescriptionHashMap.get(diagnoseId) != null) {
            isChooseMould = true;
            PrescriptionListResponse.pInfo pInfoCache = prescriptionHashMap.get(diagnoseId).pInfo.get(0);
            PrescriptionListResponse.diagInfo diagInfoCache = prescriptionHashMap.get(diagnoseId).diagInfo;
            list.clear();
            list.addAll(pInfoCache.westernList);
        }
    }

    @SuppressLint("NonConstantResourceId")
    @OnClick({R.id.mould_container, R.id.btn_guoyao, R.id.btn_yuannei, R.id.btn_add, R.id.btn_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mould_container:
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                startActivityForResult(MouldActivity.class, bundle, 1);
                break;
            case R.id.btn_guoyao:
                isGuoYao = true;
                if (type == 0 && list.size() > 0) {
                    showFinish3Dialog(0);
                }
                break;
            case R.id.btn_yuannei:
                isGuoYao = false;
                if (type == 1 && list.size() > 0) {
                    showFinish3Dialog(1);
                }
                break;
            //添加药品
            case R.id.btn_add:
                if (btn_yuannei.isChecked()) {
                    showSelectHeadPicDialog(0);
                }
//                if (btn_guoyao.isChecked()) {
//                    showSelectHeadPicDialog(1);
//                }
                break;
            case R.id.btn_confirm:
//                isClearMould = true;
                showProgressDialog(mContext);
                save();
//                queryOauthStatus();
//                showSaveDialog();
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + view.getId());
        }
    }

    /**
     * 查询授权状态接口
     */
    public void queryOauthStatus() {
        RestProxy.getInstance().queryOauthStatus(new Observer<OauthStatusResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OauthStatusResponse oauthStatusResponse) {
                save();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                if (e instanceof BusinessException) {
                    if (((BusinessException) e).errorCode == 2300) {
                        authOauth();
                    } else {
                        ToastUtil.onError(mContext, e);
                    }
                }
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 授权接口
     */
    public void authOauth() {
        RestProxy.getInstance().authOauth(new Observer<AuthOauthVo>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(AuthOauthVo authOauthVo) {
                Bundle bundle = new Bundle();
                bundle.putString("url", authOauthVo.data.oauthURL);
                bundle.putInt("type", 1);
                startActivityForResult(SignatureActivity.class, bundle, 2000);
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
            }

            @Override
            public void onComplete() {
                dismissProgressDialog();
            }
        });
    }

    private void save() {
        if (btn_yuannei.isChecked()) {
            type = 0;
        }
        if (btn_guoyao.isChecked()) {
            type = 1;
        }
        LogUtil.e("模板saveicdID---", icdId);

        RestProxy.getInstance().savePrescriptionList(diagnoseId, edt_notice.getText().toString(), prescriptionId, type + "", list, new Observer<BaseStringResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseStringResponse baseResponse) {
                dismissProgressDialog();
                finish();
                EventBus.getDefault().post(new PrescriptionAchieveEvent());
//                prescriptionId = baseResponse.data;
//                Bundle bundle = new Bundle();
//                bundle.putString("prescriptionId", baseResponse.data);
//                startActivity(CheckPrescriptionStatusActivity.class, bundle);
//                bundle.putString("orderId", baseResponse.data);
//                startActivity(AtyOrderMedicineDetailActivity.class, bundle);
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    /**
     * 选择处方模板回显
     *
     * @time 2020/8/28 16:12
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                mould = (MouldResponse.Mould) data.getSerializableExtra("obj");
                isChooseMould = true;
                getInfo();
            } else if (requestCode == 2000) {
                save();
            }
        }
    }


    /**
     * 获取模板详情
     *
     * @time 2020/8/28 16:16
     */
    private void getInfo() {
        RestProxy.getInstance().getPrescriptionModelList(mould.id, new Observer<MouldListResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(MouldListResponse mouldResponse) {
                type = mouldResponse.data.type;
                if (mouldResponse.data.type == 0) {
                    btn_yuannei.setChecked(true);
                } else {
                    //1是国药
                    btn_guoyao.setChecked(true);
                }
                edt_notice.setText(mouldResponse.data.remark);
                list.clear();
                list.addAll(mouldResponse.data.westernList);
                adapter.notifyDataSetChanged();

                edt_advice.setText(mouldResponse.data.diagnoseResult);
                preAppendId = mouldResponse.data.preAppendId;
                icdId = mouldResponse.data.icdId;
                LogUtil.e("模板icdID---", icdId);
                tailAppendId = mouldResponse.data.tailAppendId;
                tvMouldName.setText(mouldResponse.data.name);

                pInfo.type = type;
                pInfo.diagnoseId = diagnoseId;
                pInfo.prescriptionId = prescriptionId;
                pInfo.remark = mouldResponse.data.remark;
                pInfo.westernList = mouldResponse.data.westernList;

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(AddPrescriptionActivity.this, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    /**
     * 查询处方列表
     *
     * @time 2020/8/24 10:19
     */
    private void queryPrescriptionList() {
        RestProxy.getInstance().queryPrescriptionList(diagnoseId, new Observer<PrescriptionListResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onNext(PrescriptionListResponse prescriptionResponse) {
                PrescriptionListResponse.diagInfo diagInfo = prescriptionResponse.data.diagInfo;
                if (prescriptionResponse.data.diagInfo != null) {
                    preAppendId = prescriptionResponse.data.diagInfo.preAppendId;
                    icdId = prescriptionResponse.data.diagInfo.icdId;
                    tailAppendId = prescriptionResponse.data.diagInfo.tailAppendId;
                    edt_advice.setText(prescriptionResponse.data.diagInfo.diagnoseResult);
                    pre.setText(diagInfo.preAppend + "-" + diagInfo.icd + "-" + diagInfo.tailAppend);
                    if (!UtilList.isEmpty(prescriptionResponse.data.diagInfo.secondList)) {
                        secondDiagnose.setVisibility(View.VISIBLE);
                        list2.addAll(prescriptionResponse.data.diagInfo.secondList);
                        secondAdapter.notifyDataSetChanged();
                    } else {
                        secondDiagnose.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(AddPrescriptionActivity.this, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }


    private void showFinish3Dialog(final int type) {
        mFinish3Dialog = Finish3Dialog.newInstance(type);
        mFinish3Dialog.show(getSupportFragmentManager(), "Finish3Dialog");
        mFinish3Dialog.setmListener(new Finish3Dialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                list.clear();
                adapter.notifyDataSetChanged();
                mFinish3Dialog.dismiss();
                if (type == 0) {
                    AddPrescriptionActivity.this.type = 1;
                } else {
                    AddPrescriptionActivity.this.type = 0;
                }
            }

            @Override
            public void onCancel() {
                if (type == 0) {
                    btn_yuannei.setChecked(true);
                } else {
                    btn_guoyao.setChecked(true);
                }
                mFinish3Dialog.dismiss();
            }
        });
    }

    /**
     * 保存弹框
     *
     * @time 2020/12/1 17:03
     */
    private void showSaveDialog() {
        // 初始化点击头像弹出的对话框
        SaveDialog mSaveDialog = SaveDialog.newInstance();
        mSaveDialog.setmListener(new SaveDialog.OnItemClickListener() {
            @Override
            public void onConfirm() {
            }

            @Override
            public void onCancel() {
            }
        });
        mSaveDialog.show(getSupportFragmentManager(), "mSaveDialog");
    }


    @SuppressLint("NotifyDataSetChanged")
    private void showSelectHeadPicDialog(int type) {
        // 初始化药品
        MedicineListDialog mMedicineDialog = MedicineListDialog.newInstance(type);
        mMedicineDialog.setOnItemClickListener(p -> {
            list.add(p);
            adapter.notifyDataSetChanged();
            svAll.post(() -> svAll.fullScroll(ScrollView.FOCUS_DOWN));

        });
        mMedicineDialog.show(getSupportFragmentManager(), "mMedicineDialog");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PrescriptionAchieveEvent event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
